package com.fancy.service.imp;

import com.alibaba.fastjson.JSON;
import com.fancy.dao.RankMusicDao;
import com.fancy.pojo.category.Music;
import com.fancy.service.RankDownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class RankDownloadServiceImp implements RankDownloadService {
    @Autowired
    RankMusicDao rankMusicDao;
    @Autowired
    RedisTemplate redisTemplate;
    public static final String SCORE_RANK = "download";
    @Override
    public String rankdownload() {
        Set<ZSetOperations.TypedTuple<Music>> tuples = new HashSet<>();
        long start = System.currentTimeMillis();
        List<Music> allMusic = rankMusicDao.findAllMusic();
        for (Music music:allMusic) {
            Integer downloadQuantity = music.getDownloadQuantity();
            String s = Integer.toString(downloadQuantity);
            double v = Double.parseDouble(s);
            DefaultTypedTuple<Music> tuple = new DefaultTypedTuple<Music>(music,v);
            tuples.add(tuple);
        }
        Long num = redisTemplate.opsForZSet().add(SCORE_RANK, tuples);

        Set<String> range = redisTemplate.opsForZSet().reverseRange(SCORE_RANK, 0, 10);
        Set<ZSetOperations.TypedTuple<Music>> rangeWithScores = redisTemplate.opsForZSet().reverseRangeWithScores(SCORE_RANK, 0, 10);
        System.out.println("2获取到的排行和分数列表:" + JSON.toJSONString(rangeWithScores));
        return JSON.toJSONString(rangeWithScores);
    }

    @Override
    public String redisdownload() {
        Set<String> range = redisTemplate.opsForZSet().reverseRange(SCORE_RANK, 0, 10);
//        System.out.println("获取到的排行列表:" + JSON.toJSONString(range));
        Set<ZSetOperations.TypedTuple<Music>> rangeWithScores = redisTemplate.opsForZSet().reverseRangeWithScores(SCORE_RANK, 0, 10);
        System.out.println("2获取到的排行和分数列表:" + JSON.toJSONString(rangeWithScores));
        return JSON.toJSONString(rangeWithScores);
    }
}
